package cn.qn.flowable.controller;

import cn.qn.flowable.result.BaseResponse;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ModelController {
    private final RepositoryService repositoryService;

    /**
     * 部署流程模型.
     *
     * @return 流程key
     */
    @PostMapping("/deploy")
    public ResponseEntity<Object> createProcessDef() {
        String categoryLeave = "LEAVE";
        String nameLeave = "请假流程";

        //1,创建部署对象
        Deployment deployment = repositoryService.createDeployment()
                //2.添加流程定义文件
                .addClasspathResource("process/请假流程审批.bpmn20.xml")
                //3.设置流程名称
                .name(nameLeave)
                .category(categoryLeave)
                //4.部署
                .deploy();
        //5.返回部署的流程id
        return new ResponseEntity<>(new BaseResponse<>(deployment.getId()), HttpStatus.OK);
    }

    /**
     * 获取流程模型部署列表
     */
    @GetMapping("/process/model/deployment")
    public ResponseEntity<BaseResponse<List<Map<String, Object>>>> getProcessModelDeploymentList() {
        int pageNum = 0;
        int pageSize = 10;

        List<Deployment> deploymentList = repositoryService.createDeploymentQuery()
                .orderByDeploymentTime().desc()
                .listPage(pageNum * pageSize, pageSize);

        List<Map<String, Object>> list = new ArrayList<>();
        if (!deploymentList.isEmpty()) {
            deploymentList.forEach(deployment -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", deployment.getId());
                map.put("name", deployment.getName());
                map.put("category", deployment.getCategory());
                map.put("deploymentTime", deployment.getDeploymentTime());
                list.add(map);
            });
        }
        return new ResponseEntity<>(new BaseResponse<>(list), HttpStatus.OK);
    }

}
